﻿using System.Text.Json;
using System.Text.Json.Serialization;

namespace BPanel.Core.Middlewares;

public class JsonDateTimeConverter : JsonConverter<DateTime>
{
    private readonly string _format;

    /// <summary>
    /// 构造方法
    /// </summary>
    /// <param name="format"></param>
    public JsonDateTimeConverter(string format)
    {
        _format = format;
    }

    public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        return DateTime.ParseExact(reader.GetString() ?? "2000-01-01", _format, null);
    }

    public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value.ToString(_format));
    }
}